﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using SmartSiteManagementSystem.AdminWeb.Extensions;
using SmartSiteManagementSystem.AdminWeb.Filter;
using SmartSiteManagementSystem.AdminWeb.Models;
using SmartSiteManagementSystem.IServices;
using SmartSiteManagementSystem.Models.Material;
using SmartSiteManagementSystem.Models.DTO;
using System.Collections;
using System.IO;
using OfficeOpenXml;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using System.Text;
using System.Data;
using SmartSiteManagementSystem.Utils;

namespace SmartSiteManagementSystem.AdminWeb.Controllers
{
    /*
     ASP.NET Core 导入导出Excel xlsx 文件
ASP.NET Core 使用EPPlus.Core导入导出Excel xlsx 文件，EPPlus.Core支持Excel 2007/2010 xlsx文件导入导出，可以运行在Windows, Linux和Mac。
EPPlus.Core 是基于EPPlus 更改而来，在Linux 下需要安装libgdiplus 。
EPPlus：http://epplus.codeplex.com/
EPPlus.Core：https://github.com/VahidN/EPPlus.Core
下面在ASP.NET Core 中导入导出Excel xlsx 文件。
新建项目
新建一个ASP.NET Core Web Application 项目ASPNETCoreExcel，选择Web 应用程序 不进行身份验证。
然后添加EPPlus.Core 引用。
使用NuGet 命令行：
Install-Package EPPlus.Core
也可以使用NuGet包管理器安装。
导出xlsx文件
     
     */

    public class MaterialController : AdminBaseControllers
    {
        /// <summary>
        /// 
        /// </summary>
        private IWebHostEnvironment _webHostEnvironment ;

        private readonly ILogger<MaterialController> _logger;
        //注入后台服务
        private readonly IMaterialService _materialService;
        //注入后台服务
        private readonly IAdminService _adminService;
        public MaterialController(IAdminService adminService, IMaterialService materialService, ILogger<MaterialController> logger, IWebHostEnvironment webHostEnvironment) : base(adminService)
        {
            _logger = logger;
            _adminService = adminService;
            _materialService = materialService;
            _webHostEnvironment = webHostEnvironment;
        }

        #region 分类相关页面

        /// <summary>
        /// 首页  
        /// </summary>
        public ViewResult CatalogIndex()
        {
            return View();
        }

        public ViewResult CatalogLeft()
        {
            return View();
        }
        /// <summary>
        /// 分类树
        /// </summary>
        /// <returns></returns>
        public JsonResult CatalogTree()
        {
            
            IList<MaterialCatalogInfo> gci = _materialService.GetMaterialCatalogInfoList(null);

            IEnumerable<MaterialCatalogInfo> rootGci = gci.Where(m => m.ParentId == 0).OrderBy<MaterialCatalogInfo, int>(
                Sgci => Sgci.SortOrder
                );

            List<TreeModel> tree = new List<TreeModel>();
            TreeModel node;
            foreach (var item in rootGci)
            {
                node = new TreeModel();
                node.id = item.CatalogId;
                node.text = item.CatalogName;
                node.children = GetTreeChild(gci, item);
                node.url = "CatalogEdit?operation=edit&parentId=0&catalogId=" + node.id;
                tree.Add(node);
            }
            //return Json(tree, JsonRequestBehavior.AllowGet);
            return Json(tree);
        }
        /// <summary>
        /// 获取子分类
        /// </summary>
        /// <param name="cataloglist"></param>
        /// <param name="curNode"></param>
        /// <returns></returns>
        private List<TreeModel> GetTreeChild(IList<MaterialCatalogInfo> cataloglist, MaterialCatalogInfo curNode)
        {
            IEnumerable<MaterialCatalogInfo> childlist = cataloglist.Where(m => m.ParentId == curNode.CatalogId).OrderBy<MaterialCatalogInfo, int>(
                Sgci => Sgci.SortOrder
                );
            List<TreeModel> tree = new List<TreeModel>();
            TreeModel node;
            foreach (MaterialCatalogInfo item in childlist)
            {
                node = new TreeModel();
                node.id = item.CatalogId;
                node.text = item.CatalogName;
                if (item.IsParent)
                {
                    node.children = GetTreeChild(cataloglist, item);
                }
                node.url = "CatalogEdit?operation=edit&parentId=" + curNode.ParentId + "&catalogId=" + node.id;
                tree.Add(node);
            }
            return tree;
        }

        /// <summary>
        /// 分类编辑
        /// </summary>
        /// <param name="operation"></param>
        /// <param name="catalogId"></param>
        /// <param name="parentId"></param>
        /// <returns></returns>
        public ViewResult CatalogEdit(string operation, int catalogId, int parentId = 0)
        {
            operation = operation.ToLower();
            if (catalogId == 0)
            {
                operation = "add";
            }

            MaterialCatalogInfo parentCatalog = new MaterialCatalogInfo();
            MaterialCatalogInfo catalog = new MaterialCatalogInfo();
            if (operation == "add")
            {
                if (parentId > 0)
                {
                    parentCatalog = _materialService.GetMaterialCatalogInfoById(parentId);
                    catalog.ParentName = parentCatalog.CatalogName;
                    if ("一级分类".Equals(parentCatalog.SuperiorName))
                        catalog.SuperiorName = "二级分类";
                    if ("".Equals(parentCatalog.SuperiorName))
                        catalog.SuperiorName = "一级分类";
                }
                catalog.ParentId = parentId;
            }
            else if (operation == "edit")
            {
                catalog = _materialService.GetMaterialCatalogInfoById(catalogId);
                parentCatalog = _materialService.GetMaterialCatalogInfoById(catalog.ParentId);
                if (string.IsNullOrEmpty(catalog.SuperiorName) || "一级分类".Equals(catalog.SuperiorName))
                {
                    catalog.IsParent = true;
                }
            }

            ViewBag.Catalog = catalog;
            ViewBag.ParentCatalog = parentCatalog;
            ViewBag.CatalogId = catalogId;
            return View();
        }

        /// <summary>
        /// 分类编辑
        /// </summary>
        /// <param name="catalogId"></param>
        /// <param name="parentId"></param>
        /// <param name="sortOrder"></param>
        /// <param name="catalogName"></param>
        /// <param name="catalogLink"></param>
        /// <param name="countLadderJson"></param>
        /// <param name="keyWord"></param>
        /// <param name="stopFlog"></param>
        /// <param name="oldStopFlog"></param>
        /// <returns></returns>
        public JsonResult DoEditCatalog(int catalogId, int parentId, int sortOrder, string catalogName
            , int stopFlog = 0
            , int oldStopFlog = 0)
        {
            bool sf = stopFlog == 1;
            ResultInfo result = new ResultInfo();
            result.IsSuccess = false;
            result.Code = 200;
            result.Msg = "操作失败!";
            Hashtable param = new Hashtable();
            param.Add("sort_order", sortOrder);
            param.Add("parent_id", parentId);
            param.Add("is_stop", sf);
            param.Add("catalog_name", catalogName);
            param.Add("catalog_id", catalogId);
            int addId = 0;
            if (catalogId > 0)
            {
                if (sf && oldStopFlog == 0)
                {
                    string str = stopCatalog(catalogId);
                    if (!string.IsNullOrEmpty(str))
                    {
                        result.Msg = str;
                        result.IsSuccess = false;
                        return Json(result);
                    }
                }
                //启用该分类 判断父类是否处于停用状态
                if (!sf && oldStopFlog == 1)
                {
                    string msg = UnStopCatalog(catalogId);
                    if (!string.IsNullOrEmpty(msg))
                    {
                        result.Msg = msg;
                        result.IsSuccess = false;
                        return Json(result);
                    }
                }
                //修改
                bool updateStatus = _materialService.UpdateMaterialCatalogInfo(param);
                if(updateStatus)
                {
                    addId = 1;
                }
                else
                {
                    addId = 0;
                }
                if (sf)
                {
                    SetSubCatalogStop(catalogId);
                }
                else
                {
                    string parentCatalogIds = _materialService.GetParentCatalogIds(catalogId);
                    if (!string.IsNullOrEmpty(parentCatalogIds))
                    {
                        string[] ParentCatalogIds = parentCatalogIds.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                        foreach (var parentCatalogId in ParentCatalogIds)
                        {
                            var parentCatalogObj = _materialService.GetMaterialCatalogInfoById(Int32.Parse(parentCatalogId));
                            if (!parentCatalogObj.IsStop)
                            {
                                continue;
                            }
                            parentCatalogObj.IsStop = false;
                            parentCatalogObj.UpdateTime = DateTime.Now;
                            _materialService.UpdateMaterialCatalogInfo(parentCatalogObj);
                        }
                    }
                }

                if (addId > 0)
                {
                    result.Msg = "修改成功!";
                    result.IsSuccess = true;
                    return Json(result);
                  
                }
                else
                {
                    result.Msg = "修改失败!";
                    result.IsSuccess = false;
                    return Json(result);
                }
            }
            else
            {
                MaterialCatalogInfo catalog = new MaterialCatalogInfo();
                catalog.SortOrder = sortOrder;
                catalog.ParentId = parentId;
                catalog.IsStop = sf;
                catalog.CatalogName = catalogName;
                catalog.CreateTime = DateTime.Now;
                catalog.UpdateTime = DateTime.Now;
                //新增
                addId = _materialService.InsertMaterialCatalogInfo(catalog);
                //如果添加的节点是某节点的子节点，则更新其父节点的IsParent字段为true
                if (addId > 0 && parentId > 0)
                {
                    MaterialCatalogInfo parentCatalog = _materialService.GetMaterialCatalogInfoById(parentId);
                    if (!parentCatalog.IsParent)
                    {
                        parentCatalog.IsParent = true;
                        parentCatalog.UpdateTime = DateTime.Now;
                        _materialService.UpdateMaterialCatalogInfo(parentCatalog);
                    }
                }

                if (addId > 0)
                {
                    result.Msg = "添加成功!";
                    result.IsSuccess = true;
                    return Json(result);

                }
                else
                {
                    result.Msg = "添加失败!";
                    result.IsSuccess = false;
                    return Json(result);
                }
            }
        }

        /// <summary>
        /// 停用分类
        /// </summary>
        /// <param name="catalogId"></param>
        /// <returns></returns>
        private string stopCatalog(int catalogId)
        {
            var child = _materialService.GetChildListStopC(catalogId);
            if (child.Count > 0)
            {
                return "该分类下包含未停用的子分类，不允许停用！";
            }
            int _count = _materialService.GetMaterialInfoCountByCatalogId(catalogId);
            if (_count > 0)
            {
                return "该分类下面有物料，不允许停用！";
            }
            return null;
        }

        private string UnStopCatalog(int catalogId)
        {
            IList<MaterialCatalogInfo> infos = _materialService.GetParents(catalogId);
            string msg = "该分类父类处于停用状态，无法启用当前分类";
            foreach (MaterialCatalogInfo info in infos)
            {
                if (info.CatalogId == catalogId)
                    continue;
                if (info.IsStop)
                    return msg;
            }
            return null;
        }
        /// <summary>
        /// 设置所有子分类禁用或可用 (默认禁用)
        /// </summary>
        /// <param name="catalogId">分类Id</param>
        /// <param name="stopFlag">禁用标记</param>
        private void SetSubCatalogStop(int catalogId, bool stopFlag = true)
        {
            var catalogObjList = _materialService.GetCatalogChildList(catalogId);
            foreach (var catalogObj in catalogObjList)
            {
                if (!catalogObj.IsStop)
                {
                    catalogObj.IsStop = stopFlag;
                }
                SetSubCatalogStop(catalogObj.CatalogId);
            }
        }

        /// <summary>
        /// 删除分类
        /// </summary>
        /// <param name="catalogId"></param>
        /// <param name="parentId"></param>
        /// <returns></returns>
        public JsonResult DoDeleteCatalog(int catalogId, int parentId = 0)
        {
            ResultInfo result = new ResultInfo();
            result.IsSuccess = false;
            result.Code = 200;
            result.Msg = "操作失败!";
            var child = _materialService.GetCatalogChildList(catalogId);
            if (child.Count > 0)
            {
                result.Msg = "该分类下面有子分类，不允许删除！";
                result.IsSuccess = false;
                return Json(result);
            }
            else
            {
                int _count = _materialService.GetMaterialInfoCountByCatalogId(catalogId);
                if (_count > 0)
                {
                    result.Msg = "该分类下面有物料，不允许删除！";
                    result.IsSuccess = false;
                    return Json(result);
                }
                else
                {
                    bool uResult = _materialService.DeleteMaterialCatalog(catalogId, parentId);

                    if (uResult)
                    {
                        result.Msg = "删除成功";
                        result.IsSuccess = true;
                        return Json(result);
                    }
                    else
                    {
                        result.Msg = "删除失败";
                        result.IsSuccess = false;
                        return Json(result);
                    }
                }
            }
        }

        /// <summary>
        /// 获取所有一级类别
        /// </summary>
        /// <returns></returns>
        [SkipFilterAttribute]
        public JsonResult GetAllFirstCatalog()
        {
            Hashtable param = new Hashtable();
            param.Add("parent_id", 0);
            param.Add("is_stop", false);
            param.Add("is_deleted", false);
            IList<MaterialCatalogInfo> allFirstCatalog =_materialService.GetMaterialCatalogInfoList(param).ToList();
            MaterialCatalogInfo catalogInfo = new MaterialCatalogInfo();
            catalogInfo.CatalogId = 0;
            catalogInfo.CatalogName = "请选择";
            allFirstCatalog.Insert(0, catalogInfo);
            return Json(allFirstCatalog);
        }

        /// <summary>
        /// 通过父类别获取所有子类别
        /// </summary>
        /// <param name="parentId"></param>
        /// <returns></returns>
        [SkipFilterAttribute]
        public JsonResult GetCatalogByParentId(int parentId)
        {
            //停用和禁用的都不显示
            IList<MaterialCatalogInfo> childCatalogs = new List<MaterialCatalogInfo>();
            if (parentId > 0)
            {
                childCatalogs = _materialService.GetCatalogChildList(parentId).Where(x => x.IsStop == false).ToList();
            }
            MaterialCatalogInfo catalogInfo = new MaterialCatalogInfo();
            catalogInfo.CatalogId = 0;
            catalogInfo.CatalogName = "请选择";
            childCatalogs.Insert(0, catalogInfo);
            return Json(childCatalogs);
        }

        /// <summary>
        /// 通过第三级类别Id获取数据
        /// </summary>
        /// <param name="thirdId"></param>
        /// <returns></returns>
        [SkipFilterAttribute]
        public JsonResult GetCatalogByThirdId(int thirdId)
        {
            List<MaterialCatalogInfo> Catalogs = new List<MaterialCatalogInfo>();
            MaterialCatalogInfo catas1 = _materialService.GetMaterialCatalogInfoById(thirdId);
            if (catas1 == null || catas1.CatalogId == 0 || catas1.IsDeleted == true || catas1.IsStop == true)
            {

                return Json(Catalogs);
            }
            MaterialCatalogInfo catas2 = _materialService.GetMaterialCatalogInfoById(catas1.ParentId);

            if (catas2 == null || catas2.CatalogId == 0 || catas2.IsDeleted == true || catas2.IsStop == true)
            {
                return Json(Catalogs);
            }
            MaterialCatalogInfo catas3 = _materialService.GetMaterialCatalogInfoById(catas2.ParentId);
            if (catas3 == null || catas3.CatalogId == 0 || catas3.IsDeleted == true || catas3.IsStop == true)
            {
                return Json(Catalogs);
            }
            Catalogs.Add(catas3);
            Catalogs.Add(catas2);
            Catalogs.Add(catas1);
            return Json(Catalogs);
        }
        #endregion


        #region 物料相关页面
        /// <summary>
        ///  物料首页
        /// </summary>
        /// <returns></returns>
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 获取列表
        /// </summary>
        /// <param name="catagoryId"></param>
        /// <param name="page"></param>
        /// <param name="rows"></param>
        public JsonResult GetList(int catagoryId,string searchKey, int page = 0, int rows = 50)
        {
            if (page < 1)
            {
                page = 1;
            }
            page = (page - 1) * rows;

            Hashtable param = new Hashtable();
            param.Add("is_deleted", 0);//正常 0 false
            if (catagoryId>0)
                param.Add("catalog_id", catagoryId);
            int count =_materialService.GetMaterialInfoListCount(param);
            IList<MaterialInfo> list = _materialService.GetMaterialInfoList(param, "", page, rows);
            foreach(MaterialInfo item in list)
            {
                MaterialCatalogInfo catagory = _materialService.GetMaterialCatalogInfoById(item.CatalogId);
                if(catagory!=null)
                {
                    item.CatagoryName = catagory.CatalogName;
                }

            }
            var data = new
            {
                total = count,
                rows = list
            };
            return Json(data);

        }


        /// <summary>
        /// 更新状态
        /// </summary>
        /// <param name="materialId"></param>
        public JsonResult ajaxUpdateMaterialState(int materialId)
        {
            ResultInfo result = new ResultInfo();
            result.IsSuccess = false;
            result.Code = 200;
            result.Msg = "操作失败!";
            MaterialInfo materialInfo = null;
            if (materialId > 0)
            {
                materialInfo = _materialService.GetMaterialInfoById(materialId);
                materialInfo.UpdateTime = DateTime.Now;
                materialInfo.IsStop = materialInfo.IsStop ? false : true;
                result.IsSuccess =  _materialService.UpdateMaterialInfo(materialInfo);

            }
            if (result.IsSuccess)
            {
                result.Msg = "操作成功!";
            }
            return Json(result);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="materialId"></param>
        public JsonResult ajaxDeleteMaterial(int materialId)
        {
            ResultInfo result = new ResultInfo();
            result.IsSuccess = false;
            result.Code = 200;
            result.Msg = "操作失败!";
            if (materialId > 0)
            {
                MaterialInfo materialInfo = _materialService.GetMaterialInfoById(materialId);
                if (materialInfo != null)
                {
                    materialInfo.IsDeleted = true;
                    result.IsSuccess = _materialService.UpdateMaterialInfo(materialInfo);
                }
            }
            if (result.IsSuccess)
            {
                result.Msg = "成功删除!";
            }
            return Json(result);
        }



        /// <summary>
        /// 添加或修改
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult Access(int id = 0)
        {
            MaterialInfo materialInfo = new MaterialInfo();
            if (id > 0)
            {
                materialInfo = _materialService.GetMaterialInfoById(id);
            }
            ViewBag.materialInfo = materialInfo;

            return View();
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="MaterialId"></param>
        /// <param name="MaterialName"></param>
        /// <param name="CatalogId"></param>
        /// <param name="SingleWeight"></param>
        /// <param name="SortOrder"></param>
        /// <param name="Descript"></param>
        public JsonResult ajaxAccess(int MaterialId, string MaterialName, int CatalogId, string SingleWeight, int SortOrder, string Descript)
        {
            MaterialInfo materialInfo = null;
            ResultInfo result = new ResultInfo();
            result.IsSuccess = false;
            result.Code = 200;
            result.Msg = "操作失败!";
            if (MaterialId > 0)
            {
                materialInfo = _materialService.GetMaterialInfoById(MaterialId);
            }
            else
            {
                materialInfo = new MaterialInfo();
                materialInfo.IsStop = false;
            }
            materialInfo.IsDeleted = false;
            materialInfo.CatalogId = CatalogId;
            if(!string.IsNullOrEmpty(SingleWeight))
            {
                materialInfo.SingleWeight = decimal.Parse(SingleWeight);
            }

            materialInfo.SortOrder = SortOrder;
            materialInfo.Descript = Descript;
            materialInfo.MaterialName = MaterialName;

            if (MaterialId > 0)
            {
                result.IsSuccess = _materialService.UpdateMaterialInfo(materialInfo);

            }
            else
            {
                MaterialId = _materialService.InsertMaterialInfo(materialInfo);
                result.IsSuccess = MaterialId > 0 ? true : false;
            }
            if (result.IsSuccess)
            {
                result.Msg = "操作成功!";
            }
            return Json(result);
        }

        #region excel导出导入

        /*
    ASP.NET Core 导入导出Excel xlsx 文件
ASP.NET Core 使用EPPlus.Core导入导出Excel xlsx 文件，EPPlus.Core支持Excel 2007/2010 xlsx文件导入导出，可以运行在Windows, Linux和Mac。
EPPlus.Core 是基于EPPlus 更改而来，在Linux 下需要安装libgdiplus 。
EPPlus：http://epplus.codeplex.com/
EPPlus.Core：https://github.com/VahidN/EPPlus.Core
下面在ASP.NET Core 中导入导出Excel xlsx 文件。
新建项目
新建一个ASP.NET Core Web Application 项目ASPNETCoreExcel，选择Web 应用程序 不进行身份验证。
然后添加EPPlus.Core 引用。
使用NuGet 命令行：
Install-Package EPPlus.Core
也可以使用NuGet包管理器安装。
导出xlsx文件

    */

        /// <summary>
        /// 导出excel
        /// https://www.cnblogs.com/kevinN/p/15151905.html
        /// </summary>
        /// <returns></returns>
        public IActionResult ExcelExport()
        {
            //获取网站的目录
            string sWebRootFolder = _webHostEnvironment.WebRootPath;
            
            string temWebRootFolder = sWebRootFolder + "/exportfile/";
            //随机生成的文件名
            string sFileName = $"{Guid.NewGuid()}.xlsx";
            FileInfo file = new FileInfo(Path.Combine(temWebRootFolder, sFileName));
            ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
            byte[] by = null;
            using (ExcelPackage package = new ExcelPackage(file))
            {
                //add worksheet
                ExcelWorksheet workSheet = package.Workbook.Worksheets.Add("AspNetCore");
                //add table header
                workSheet.Cells[1, 1].Value = "ID";
                workSheet.Cells[1, 2].Value = "Name";
                workSheet.Cells[1, 3].Value = "Gender";
                workSheet.Cells[1, 4].Value = "Age";
                workSheet.Cells[1, 5].Value = "Remark";

                //Add value
                workSheet.Cells["A2"].Value = 1000;
                workSheet.Cells["B2"].Value = "张三";
                workSheet.Cells["C2"].Value = "男";
                workSheet.Cells["D2"].Value = 25;
                workSheet.Cells["E2"].Value = "ABCD";

                workSheet.Cells["A3"].Value = 1001;
                workSheet.Cells["B3"].Value = "李四";
                workSheet.Cells["C3"].Value = "女";
                workSheet.Cells["D3"].Value = 35;
                workSheet.Cells["D3"].Style.Font.Bold = true;

                workSheet.Cells["A4"].Value = 1003;
                workSheet.Cells["B4"].Value = "Amy";
                workSheet.Cells["C4"].Value = "Female";
                workSheet.Cells["D4"].Value = 22;
                workSheet.Cells["E4"].Value = "Hello world";

                workSheet.Cells["A5"].Value = 1004;
                workSheet.Cells["B5"].Value = "Jim";
                workSheet.Cells["C5"].Value = "Male";
                workSheet.Cells["D5"].Value = 35;
                workSheet.Cells["E5"].Value = 500;

                package.Save();
                by=package.GetAsByteArray();
            }
            
            return File(by, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", sFileName);

        }


        /// <summary>
        /// 批量导入物料页面 zhitian.zhang
        /// </summary>
        public ActionResult import()
        {
            return View();

        }




        /// <summary>
        /// 
        /// 批量导入物料页面 选择EXCEL文件并对其做验证并把结果返回到前台页面 zhitian.zhang
        /// </summary>
        /// <param name="excelFile"></param>
        /// <returns></returns>
        /*[SkipFilter]
        [HttpPost]
        public JsonResult SelectImportFile(IFormFile excelFile )
        {
            //详细的对象定义在最底部
            ValidateImportMaterialInfo importMaterialData = new ValidateImportMaterialInfo();
            importMaterialData.AllDataIsOk = false;
            importMaterialData.AllDataMsg = string.Empty;
            importMaterialData.Total = 0;
            try
            {
                importMaterialData.Rows = new List<ValidateImportMaterialDataItem>();
                string msg = string.Empty;
                DataTable dt = ExcelHelper.GetExcelFileDataToDataTable(excelFile.FileName,true);
                if (msg.Length > 0)
                {
                    importMaterialData.AllDataMsg = ErrorRedFont(msg);
                    importMaterialData.Total = 0;
                    importMaterialData.AllDataIsOk = false;
                    importMaterialData.Rows = new List<ValidateImportMaterialDataItem>();
                }
                else
                {
                    #region  读取Excel没有报错
                    if (ds == null || ds.Tables.Count == 0)
                    {
                        importMaterialData.AllDataMsg = ErrorRedFont("文件中没有数据，请确认后再试！");
                        importMaterialData.AllDataIsOk = false;
                        importMaterialData.Total = 0;
                        importMaterialData.Rows = new List<ValidateImportMaterialDataItem>();
                    }
                    else
                    {
                        #region 读取excel有数据
                        DataTable dt = ds.Tables[0];
                        importMaterialData.Total = dt.Rows.Count;
                        IList<ValidateImportMaterialDataItem> ImportOrderDataItemList = new List<ValidateImportMaterialDataItem>();
                        #region 循环Excel数据进行验证,并给返回页面显示的数据赋值
                        int rowNuber = 1;
                        foreach (DataRow mydr in dt.Rows)
                        {
                            ValidateImportMaterialDataItem item = ValidateImportMaterialDataItem(mydr, rowNuber); //数据进行处理并检测数据合法性
                            if (item.OrderIDDataIsOk == true && item.ShopUserInfoStrDataIsOk == true && item.SupplierInfoStrDataIsOk == true
                                && item.GoodsInfoStrDataIsOk == true && item.AddressInfoStrDataIsOk == true && item.PaywayStrDataIsOk == true
                                ) //一行中所有列的数据都正确
                            {
                                item.DataIsOk = true;
                                item.DataMsg = SucGreenFont("检测通过");
                            }
                            else
                            {
                                #region  行数据有问题
                                item.DataIsOk = false;
                                StringBuilder itemErrorMsg = new StringBuilder();
                                itemErrorMsg.Append("行" + rowNuber.ToString() + ":");
                                if (item.OrderIDDataIsOk == false)
                                {
                                    itemErrorMsg.Append("订单号出了问题；");
                                }
                                if (item.ShopUserInfoStrDataIsOk == false)
                                {
                                    itemErrorMsg.Append("用户信息出了问题；");
                                }
                                if (item.SupplierInfoStrDataIsOk == false)
                                {
                                    itemErrorMsg.Append("供应商信息出了问题；");
                                }
                                if (item.GoodsInfoStrDataIsOk == false)
                                {
                                    itemErrorMsg.Append("商品信息出了问题；");
                                }
                                if (item.AddressInfoStrDataIsOk == false)
                                {
                                    itemErrorMsg.Append("地址信息出了问题；");
                                }
                                if (item.PaywayStrDataIsOk == false)
                                {
                                    itemErrorMsg.Append("支付方式信息出了问题；");
                                }
                                item.DataMsg = ErrorRedFont(itemErrorMsg.ToString());
                                #endregion
                            }
                            rowNuber++;
                            ImportOrderDataItemList.Add(item);
                        }

                        importOrderData.Rows = ImportOrderDataItemList;
                        #endregion
                        #region 检测每一行是否都通过
                        bool temiAllDataIsOk = true;
                        string temiAllDataIsOkMsg = SucGreenFont("上传的数据木有问题");
                        foreach (ValidateImportOrderDataItem item in importOrderData.Rows)
                        {
                            if (item.DataIsOk == false)  //只要有一行有问题设置为数据有问题
                            {
                                temiAllDataIsOk = false;
                                temiAllDataIsOkMsg = ErrorRedFont("请检查标红的数据有问题");
                                break;
                            }
                        }
                        #endregion
                        #region zhitian.zhang 新增判断是否用余额支付
                        OrderPayWayEnum payway = OrderPayWayEnum.账户余额;
                        #endregion
                        bool UserAmountCanPay = false; //账户余额是否足够支付
                        string UserAmountCanPayMsg = ErrorRedFont("Error");
                        #region 判断账号余额是否够支付导入订单
                        if (GetValidateImportOrderDataListUserIsOKState(importOrderData.Rows)
                            && GetValidateImportOrderDataListGoodsInfoStrDataIsOkState(importOrderData.Rows)
                            ) //如果检验每一行用户ID以及商品信息是否可以转换为实体类，只能能转才有判断账号是否够钱支付的意义
                        {
                            #region 数据可以转化
                            IList<ImportOrderDataItem> dataList = ConverToJustGoodsAndUserInfoAllImportOrderDataItem(dt);

                            #region 判断是否是只有一个用户
                            int userId = -1;
                            int paywayInt = 0;
                            bool onlyOneUser = true;
                            bool onlyOnePayway = true;
                            if (dataList.Count > 0)
                            {
                                userId = dataList[0].ShopUserId;
                                int.TryParse(dataList[0].Payway, out paywayInt);
                            }
                            foreach (ImportOrderDataItem item in dataList)
                            {
                                if (item.ShopUserId != userId)
                                {
                                    onlyOneUser = false;
                                    break;
                                }
                                if (paywayInt > 0)
                                {
                                    if (int.Parse(item.Payway) != paywayInt)
                                    {
                                        onlyOnePayway = false;
                                        break;
                                    }
                                }
                            }
                            #endregion

                            #region 判断是否只有一种支付方式
                            if ((paywayInt == (int)OrderPayWayEnum.账户余额 || paywayInt == (int)OrderPayWayEnum.通联微信支付 || paywayInt == (int)OrderPayWayEnum.通联网银网关支付) && onlyOnePayway)
                            {
                                if (paywayInt == (int)OrderPayWayEnum.通联微信支付)
                                {
                                    payway = OrderPayWayEnum.通联微信支付;
                                }
                                else if (paywayInt == (int)OrderPayWayEnum.通联网银网关支付)
                                {
                                    payway = OrderPayWayEnum.通联网银网关支付;
                                }
                                #region 判断店主ID是否同一个
                                if (onlyOneUser && userId > 0)
                                {
                                    #region 算出excel的总价
                                    decimal buyTotal = 0;
                                    foreach (ImportOrderDataItem item in dataList)
                                    {
                                        buyTotal = buyTotal + item.Total;
                                    }
                                    #endregion
                                    //订单信息
                                    TUserAccountInfo userAccountInfo = QiJuMainService.TUserAccountBLL.Get(userId);
                                    if (userAccountInfo != null)
                                    {
                                        if (payway == OrderPayWayEnum.账户余额)
                                        {
                                            #region 余额支付方式下判断余额是否足够支付
                                            if (userAccountInfo.AmountCanUse >= buyTotal && buyTotal > 0)
                                            {
                                                UserAmountCanPay = true; //账户余额是够支付
                                                UserAmountCanPayMsg = SucGreenFont("当前账号（" + userId + "）账号余额为" + userAccountInfo.AmountCanUse + "足够支付商品的总金额" + buyTotal + "");
                                            }
                                            else
                                            {
                                                UserAmountCanPay = false;
                                                if (buyTotal <= 0)
                                                {
                                                    UserAmountCanPayMsg = ErrorRedFont("全部商品的总金额不能小于等于0!");
                                                }
                                                else
                                                {
                                                    UserAmountCanPayMsg = ErrorRedFont("当前账号（" + userId + "）账号余额为" + userAccountInfo.AmountCanUse + "不足支付商品的总金额" + buyTotal + "");
                                                }
                                            }
                                            #endregion
                                        }
                                        else if (payway == OrderPayWayEnum.通联微信支付 || payway == OrderPayWayEnum.通联网银网关支付) //zhitian.zhang 20190710 add
                                        {
                                            UserAmountCanPay = true; //账户余额默认判断通过
                                            UserAmountCanPayMsg = SucGreenFont("使用通联支付方式导入订单为未付款状态");
                                        }
                                        else
                                        {
                                            UserAmountCanPay = false;
                                            UserAmountCanPayMsg = ErrorRedFont("支付方式不正确：只支持余额支付3或通联微信支付4!");
                                        }
                                    }
                                    else
                                    {
                                        UserAmountCanPay = false;
                                        UserAmountCanPayMsg = ErrorRedFont("不存在" + userId.ToString() + "账号信息!");
                                    }
                                }
                                else
                                {
                                    UserAmountCanPay = false;
                                    UserAmountCanPayMsg = ErrorRedFont("系统不支持多个shopuserid导单!");
                                }
                                #endregion
                            }
                            else
                            {
                                UserAmountCanPay = false;
                                if (!onlyOnePayway)
                                {
                                    UserAmountCanPayMsg = ErrorRedFont("系统不支持多种支付方式导单!");
                                }
                                else
                                {
                                    UserAmountCanPayMsg = ErrorRedFont("支付方式不正确：只支持余额支付3或通联微信支付4!");
                                }
                            }
                            #endregion
                            #endregion

                        }
                        #endregion
                        //数据没有问题，并且余额足够支付
                        if (temiAllDataIsOk == true && UserAmountCanPay == true)
                        {
                            importOrderData.AllDataIsOk = true;
                            importOrderData.AllDataMsg = UserAmountCanPayMsg + ";" + temiAllDataIsOkMsg;

                        }
                        else
                        {
                            importOrderData.AllDataIsOk = false;
                            importOrderData.AllDataMsg = UserAmountCanPayMsg + ";" + temiAllDataIsOkMsg;
                        }
                        #endregion

                    }
                    #endregion
                }
            }
            catch (Exception ex)
            {
                importMaterialData.AllDataMsg = ErrorRedFont("数据异常，请联系管理员！");
                importMaterialData.Total = 0;
                importMaterialData.AllDataIsOk = false;
                importMaterialData.Rows = new List<ValidateImportMaterialDataItem>();

                _logger.LogError("物料导入出错详情：" + ex);
            }

            var json = new
            {
                total = importMaterialData.Rows.Count,
                allDataIsOk = importMaterialData.AllDataIsOk,
                allDataMsg = importMaterialData.AllDataMsg,
                rows = importMaterialData.Rows
            };
            return Json(json);

        }*/



        /// <summary>
        /// https://blog.csdn.net/baidu_39298625/article/details/106189630
        /// </summary>
        /// <param name="excelFile"></param>
        /// <returns></returns>
        public IActionResult OnPostImport(IFormFile excelFile)
        {
            ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
            string sWebRootFolder = _webHostEnvironment.WebRootPath;
            string sFileName = $"{Guid.NewGuid()}.xlsx";
            FileInfo file = new FileInfo(Path.Combine(sWebRootFolder, sFileName));
            try
            {
                using (FileStream fs = new FileStream(file.ToString(), FileMode.Create))
                {
                    excelFile.CopyTo(fs);
                    fs.Flush();
                }
                using (ExcelPackage package = new ExcelPackage(file))
                {
                    StringBuilder sb = new StringBuilder();
                    ExcelWorksheet worksheet = package.Workbook.Worksheets[0];
                    int rowCount = worksheet.Dimension.Rows;
                    int colCount = worksheet.Dimension.Columns;
                    bool bheaderRow = true;
                    for (int row = 1; row <= rowCount; row++)
                    {
                        for (int col = 1; col <= colCount; col++)
                        {
                            if (bheaderRow)
                            {
                                if (worksheet.Cells[row, col].Value != null)
                                {
                                    sb.Append(worksheet.Cells[row, col].Value.ToString() + "\t");
                                }
                                else
                                {
                                    sb.Append("\t");
                                }
                            }
                            else
                            {
                                if (worksheet.Cells[row, col].Value != null)
                                {
                                    sb.Append(worksheet.Cells[row, col].Value.ToString() + "\t");
                                }
                                else
                                {
                                    sb.Append("\t");
                                }
                            }
                        }
                        sb.Append(Environment.NewLine);
                        if (bheaderRow)
                        {
                            sb.Append("-----------------------------------------");
                            sb.Append(Environment.NewLine);
                        }
                        bheaderRow = false;
                    }
                    return Content(sb.ToString());
                }
            }
            catch (Exception ex)
            {
                return Content(ex.Message);
            }
        }





        #endregion



        #endregion

    }


    #region 验证使用的对象
    /// <summary>
    /// 
    /// </summary>
    [Serializable]
    public class ValidateImportMaterialInfo
    {

        /// <summary>
        /// excel多少条记录
        /// </summary>
        private int _total = 0;
        public int Total
        {
            get { return _total; }
            set { _total = value; }
        }

        /// <summary>
        /// 返回的数据记录集合
        /// </summary>
        private IList<ValidateImportMaterialDataItem> _rows;
        public IList<ValidateImportMaterialDataItem> Rows
        {
            get { return _rows; }
            set { _rows = value; }
        }

        /// <summary>
        /// 信息是否全部OK flase 信息有问题  true 信息没有问题
        /// </summary>
        private bool _allDataIsOk;
        public bool AllDataIsOk
        {
            get { return _allDataIsOk; }
            set { _allDataIsOk = value; }
        }


        /// <summary>
        /// 信息验证提示
        /// </summary>
        private string _allDataMsg;
        public string AllDataMsg
        {
            get { return _allDataMsg; }
            set { _allDataMsg = value; }
        }

    }

    /// <summary>
    /// 验证每一行excel数据
    /// </summary>
    public class ValidateImportMaterialDataItem
    {

        /// <summary>
        /// 物料名称
        /// </summary>
        private string _materialName;
        public string MaterialName
        {
            get { return _materialName; }
            set { _materialName = value; }
        }

        /// <summary>
        /// 分类信息
        /// </summary>
        private string _catagoryName;
        public string CatagoryName
        {
            get { return _catagoryName; }
            set { _catagoryName = value; }
        }



        /// <summary>
        /// 分类信息是否OK
        /// </summary>
        private bool _catagoryNameDataIsOk;
        public bool CatagoryNameDataIsOk
        {
            get { return _catagoryNameDataIsOk; }
            set { _catagoryNameDataIsOk = value; }
        }



        /// <summary>
        /// 物料净重
        /// </summary>
        private string _singleWeight;
        public string SingleWeight
        {
            get { return _singleWeight; }
            set { _singleWeight = value; }
        }




        /// <summary>
        /// 物料净重数据是否OK
        /// </summary>
        private bool _singleWeightDataIsOk;
        public bool SingleWeightDataIsOk
        {
            get { return _singleWeightDataIsOk; }
            set { _singleWeightDataIsOk = value; }
        }



        /// <summary>
        /// 信息是否有问题 flase 信息有问题  true 信息没有问题
        /// </summary>
        private bool _dataIsOk;
        public bool DataIsOk
        {
            get { return _dataIsOk; }
            set { _dataIsOk = value; }
        }

        /// <summary>
        /// 信息验证提示
        /// </summary>
        private string _dataMsg;
        public string DataMsg
        {
            get { return _dataMsg; }
            set { _dataMsg = value; }
        }

        /// <summary>
        /// 第几行
        /// </summary>
        private int _rowNuber;
        public int RowNuber
        {
            get { return _rowNuber; }
            set { _rowNuber = value; }
        }

    }
    #endregion


    #region EXXCEL每行转换对象
    public class ImportOrderDataItem
    {

        /// <summary>
        /// 第几行
        /// </summary>
        private int _rowNuber;
        public int RowNuber
        {
            get { return _rowNuber; }
            set { _rowNuber = value; }
        }

        /// <summary>
        /// 订单号
        /// </summary>
        private decimal _orderId;
        public decimal OrderId
        {
            get { return _orderId; }
            set { _orderId = value; }
        }

        /// <summary>
        /// 店主ID
        /// </summary>
        private int _shopUserId;
        public int ShopUserId
        {
            get { return _shopUserId; }
            set { _shopUserId = value; }
        }


        /// <summary>
        /// 供应商ID
        /// </summary>
        private int _supplierId;
        public int SupplierId
        {
            get { return _supplierId; }
            set { _supplierId = value; }
        }

        /// <summary>
        /// 商品ID
        /// </summary>
        private int _goodsId;
        public int GoodsId
        {
            get { return _goodsId; }
            set { _goodsId = value; }
        }



        /// <summary>
        /// skuID
        /// </summary>
        private int _skuId;
        public int SkuId
        {
            get { return _skuId; }
            set { _skuId = value; }
        }


        /// <summary>
        /// 商品数量
        /// </summary>
        private int _goodsCount;
        public int GoodsCount
        {
            get { return _goodsCount; }
            set { _goodsCount = value; }
        }


        /// <summary>
        /// 总价
        /// </summary>
        private decimal _total;
        public decimal Total
        {
            get { return _total; }
            set { _total = value; }
        }


        /// <summary>
        /// province
        /// </summary>
        private int _province;
        public int Province
        {
            get { return _province; }
            set { _province = value; }
        }
        /// <summary>
        /// City
        /// </summary>
        private int _city;
        public int City
        {
            get { return _city; }
            set { _city = value; }
        }

        /// <summary>
        /// Zone
        /// </summary>
        private int _zone;
        public int Zone
        {
            get { return _zone; }
            set { _zone = value; }
        }

        /// <summary>
        /// 地址信息
        /// </summary>
        private string _address;
        public string Address
        {
            get { return _address; }
            set { _address = value; }
        }
        /// <summary>
        /// 收件人信息
        /// </summary>
        private string _truename;
        public string Truename
        {
            get { return _truename; }
            set { _truename = value; }
        }
        /// <summary>
        /// 手机
        /// </summary>
        private string _mobileno;
        public string Mobileno
        {
            get { return _mobileno; }
            set { _mobileno = value; }
        }


        /// <summary>
        /// 身份证
        /// </summary>
        private string _idCard;
        public string IdCard
        {
            get { return _idCard; }
            set { _idCard = value; }
        }

        /// <summary>
        /// 身份证正面图片
        /// </summary>
        private string _photoA;
        public string PhotoA
        {
            get { return _photoA; }
            set { _photoA = value; }
        }

        /// <summary>
        /// 身份证反面图片
        /// </summary>
        private string _photoB;
        public string PhotoB
        {
            get { return _photoB; }
            set { _photoB = value; }
        }


        /// <summary>
        /// 支付方式    通联支付新增  zhitian.zhang 20190710 add
        /// </summary>
        private string _payway;
        public string Payway
        {
            get { return _payway; }
            set { _payway = value; }
        }

    }
    #endregion





}
